## package language

window.language = {}

## private

$school_languages = {}

start_add_language = ->
  $('#add-language').modal()

confirm_add_language = ->
  console.log "Confirming add language"
  la = $('#language-select').val()
  $school_languages[la] = []
  if $('#101-checkbox').attr 'checked'
    $school_languages[la].push '101'
  if $('#201-checkbox').attr 'checked'
    $school_languages[la].push '201'
  if $('#301-checkbox').attr 'checked'
    $school_languages[la].push '301'
  try_save_language la, ->
    show_language la, $school_languages[la]

show_language = (la, cl) ->
  tbody = ""
  if _.contains(cl, '101')
    tbody += "<tr><td>101</td></tr>"
  if _.contains(cl, '201')
    tbody += "<tr><td>201</td></tr>"
  if _.contains(cl, '301')
    tbody += "<tr><td>301</td></tr>"
  if $("##{la}-display").length > 0
    $("#{la}-display").remove()
  $('#class-display').prepend """
    <table id="#{la}-display" class="table-bordered span2 textcenter" style="height:300px">
      <thead><tr><th>#{la}</th></tr></thead>
      <tbody>
        #{tbody}
        <tr><td><a class="btn btn-dark btn-small" onclick="language.remove('#{la}')">Remove</a></td></tr>
      </tbody>
    </table>
  """

try_save_language = (la, callback) ->
  $.post '/school/languages/save', { i: app.school_id, tk: app.token, la: la, cl: $school_languages[la].join(',') }, (data) ->
    if data.error
      $.meow { message: "The server doesn't like your values ... Refresh the page and try again, and if that doesn't work <a target='_blank' href='/contact'>contact us</a>." }
    else
      callback()
    hide_add_language()

hide_add_language = ->
  console.log "Hiding add language"
  $('#add-language').modal 'hide'

## public

language.remove = (la) ->
  $.post '/school/languages/remove', { i: app.school_id, tk: app.token, la: la }, (data) ->
    if data.error
      $.meow { message: "Hmm, removing that language didn't work ... Refresh the page and try again, and if that doesn't work <a target='_blank' href='/contact'>contact us</a>." }
    else
      $("##{la}-display").remove()

## initialize

language.initialize = (data) ->
  for sl in data.sl
    show_language LANGUAGE_NAME[sl.la], sl.cl
  $('#add-language-btn').click start_add_language
  $('#confirm-language-btn').click confirm_add_language
  $('#cancel-language-btn').click hide_add_language
